import os
import cv2 as cv
import pandas as pd
from skimage.metrics import structural_similarity
from service.info import Base_Info
from service.utils import get_roi_mat, save_json
from source.runner.paint_area import paint_rect


def to_gray(image):
    img = cv.imread(image, 1)
    gray_image = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    return gray_image


def update_result(data_path, confidence, replay_image_path):
    df = pd.read_csv(data_path, index_col=0)
    df["相似度"] = ''
    df["结果"] = ''
    for k, v in confidence.items():
        df.iloc[int(k)-1, 5] = v
        if v == -1:
            df.iloc[int(k)-1, 6] = '错误'
        elif -1 < float(v) < 0.985:
            df.iloc[int(k)-1, 6] = '失败'
        elif float(v) >= 0.985:
            df.iloc[int(k)-1, 6] = '通过'
    replay_data_path = os.path.join(
        replay_image_path.split('runtime_image')[0], data_path.split('/')[-1])
    df.to_csv(replay_data_path, encoding='utf_8_sig')
    # paint_roi(replay_data_path, replay_image_path)
    info = Base_Info()
    env_info = os.path.join(
        replay_image_path.split('runtime_image')[0], '测试环境信息')
    save_json(env_info, info.base_info())
    print("比对结果:", confidence)


def paint_roi(data, image_path):
    if os.path.exists(data):
        paint_rect(data, image_path)


def sim_compare(expect_image_path, replay_image_path, data_path, image_name, algo):
    confidence = {}
    for i in image_name:
        source = os.path.join(expect_image_path, i)
        dest = os.path.join(replay_image_path, i)
        if os.path.exists(source) and os.path.exists(dest):
            except_img = cv.imread(source)
            replay_img = cv.imread(dest)
            expect_w = except_img.shape[0]
            except_h = except_img.shape[1]
            replay_w = replay_img.shape[0]
            replay_h = replay_img.shape[1]
            if expect_w == replay_w and except_h == replay_h:
                step = int(i.split('.png')[0])
                except_roi = get_roi_mat(source, data_path, step)
                run_roi = get_roi_mat(dest, data_path, step)
                if except_roi.shape[0] < 5 or except_roi.shape[1] < 5:
                    except_roi = cv.resize(except_roi, (7, 7))
                if run_roi.shape[0] < 5 or run_roi.shape[1] < 5:
                    run_roi = cv.resize(run_roi, (7, 7))
                score, _ = structural_similarity(
                    im1=except_roi, im2=run_roi, win_size=3, gaussian_weights=True, full=True)
                index = str(i).split('.')[0]
                confidence.update({index: round(score, 4)})
            else:
                index = str(i).split('.')[0]
                confidence.update({index: -1})
    update_result(data_path, confidence, replay_image_path)
